<template>
  <div class="user-list-container">
    <div class="header-actions">
      <h2>用户管理</h2>
      <el-button type="primary" @click="showAddDialog = true">添加用户</el-button>
    </div>

    <el-table :data="users" v-loading="loading" border stripe>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="nickname" label="昵称"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="showAddDialog" :title="dialogTitle">
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item v-if="!currentUserId" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api/userApi'
import { userFormRules } from '@/utils/formRules'

const users = ref([])
const loading = ref(false)
const showAddDialog = ref(false)
const userFormRef = ref(null)
const dialogTitle = ref('添加用户')
const currentUserId = ref(null)

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const userForm = ref({
  username: '',
  nickname: '',
  email: '',
  password: ''
})

// 获取用户列表
const getUsers = async () => {
  loading.value = true
  try {
    const response = await userApi.getUsers(currentPage.value, pageSize.value)
    users.value = response.data.content
    total.value = response.data.totalElements
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 添加/编辑用户提交
const handleSubmit = async () => {
  if (!userFormRef.value) return
  try {
    await userFormRef.value.validate()
    if (currentUserId.value) {
      // 更新用户（不包含密码字段）
      const { password, ...updateData } = userForm.value
      const response = await userApi.updateUser(currentUserId.value, updateData)
      console.log(response)
      // 确保响应存在且格式正确
      if (response && response.success) {
        ElMessage.success('用户更新成功')
      } else {
        ElMessage.error(response.message || '更新失败，请重试')
      }
    } else {
      // 创建用户
      const response = await userApi.createUser(userForm.value)
      if (response && response.success) {
        ElMessage.success('用户创建成功')
      } else {
        ElMessage.error(response.message || '创建失败，请重试')
      }
    }
    showAddDialog.value = false
    getUsers()
    resetForm()
  } catch (error) {
    console.error('提交用户失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 编辑用户
const handleEdit = async (row) => {
  dialogTitle.value = '编辑用户'
  currentUserId.value = row.id
  try {
    const response = await userApi.getUser(row.id)
    userForm.value = response.data
    // 清除密码字段（编辑时不显示密码）
    delete userForm.value.password
    showAddDialog.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 删除用户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await userApi.deleteUser(id)
    ElMessage.success('用户删除成功')
    getUsers()
  } catch (error) {
    console.error('删除用户失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 重置表单
const resetForm = () => {
  userForm.value = {
    username: '',
    nickname: '',
    email: '',
    password: ''
  }
  currentUserId.value = null
  dialogTitle.value = '添加用户'
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUsers()
}

onMounted(() => {
  getUsers()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>